﻿using System;
using System.Security.Cryptography;

namespace Noria.Web.MyMSDN
{
    internal class SimpleRSA
    {
        /// <summary>
        /// Create a RSA key pair
        /// </summary>
        public static Tuple<byte[], byte[]> CreateKey()
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                var publicKey = rsa.ExportCspBlob(false);
                var keyPair = rsa.ExportCspBlob(true);
                return new Tuple<byte[], byte[]>(publicKey, keyPair);
            }
        }

        /// <summary>
        /// Encrypt data using public key
        /// </summary>
        public static byte[] Encrypt(byte[] data, byte[] key)
        {
            if (data == null || key == null)
                throw new ArgumentNullException("data" + "key");

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(key);
                return rsa.Encrypt(data, false);
            }
        }

        /// <summary>
        /// Decrypt data using private key
        /// </summary>
        public static byte[] Decrypt(byte[] data, byte[] key)
        {
            if (data == null || key == null)
                throw new ArgumentNullException("data" + "key");

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(key);
                return rsa.Decrypt(data, false);
            }
        }
    }
}